import i18n from '@/main.js';
export const forEach = (arr, fn) => {
    if (!arr.length || !fn) return;
    let i = -1;
    const len = arr.length;
    while (++i < len) {
        const item = arr[i];
        fn(item, i, arr);
    }
};

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的交集, 两个数组的元素为数值或字符串
 */
export const getIntersection = (arr1, arr2) => {
    const len = Math.min(arr1.length, arr2.length);
    let i = -1;
    const res = [];
    while (++i < len) {
        const item = arr2[i];
        if (arr1.indexOf(item) > -1) res.push(item);
    }
    return res;
};

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的并集, 两个数组的元素为数值或字符串
 */
export const getUnion = (arr1, arr2) => {
    return Array.from(new Set([...arr1, ...arr2]));
};

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (targetarr, arr) => {
    return targetarr.some(_ => arr.indexOf(_) > -1);
};

/**
 * @param {String|Number} value 要验证的字符串或数值
 * @param {*} validList 用来验证的列表
 */
export function oneOf(value, validList) {
    for (let i = 0; i < validList.length; i++) {
        if (value === validList[i]) {
            return true;
        }
    }
    return false;
}

/**
 * @param {Number} timeStamp 判断时间戳格式是否是毫秒
 * @returns {Boolean}
 */
const isMillisecond = timeStamp => {
    const timeStr = String(timeStamp);
    return timeStr.length > 10;
};

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} currentTime 当前时间时间戳
 * @returns {Boolean} 传入的时间戳是否早于当前时间戳
 */
const isEarly = (timeStamp, currentTime) => {
    return timeStamp < currentTime;
};

/**
 * @param {Number} num 数值
 * @returns {String} 处理后的字符串
 * @description 如果传入的数值小于10，即位数只有1位，则在前面补充0
 */
const getHandledValue = num => {
    return num < 10 ? '0' + num : num;
};

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} startType 要返回的时间字符串的格式类型，传入'year'则返回年开头的完整时间
 */
export const getDate = (timeStamp, startType) => {
    const d = new Date(timeStamp);
    const year = d.getFullYear();
    const month = getHandledValue(d.getMonth() + 1);
    const date = getHandledValue(d.getDate());
    const hours = getHandledValue(d.getHours());
    const minutes = getHandledValue(d.getMinutes());
    const second = getHandledValue(d.getSeconds());
    let resStr = '';
    if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second;
    else resStr = month + '-' + date + ' ' + hours + ':' + minutes;
    return resStr;
};

/**
 * @param {String|Number} timeStamp 时间戳
 * @returns {String} 相对时间字符串
 */
export const getRelativeTime = timeStamp => {
    // 判断当前传入的时间戳是秒格式还是毫秒
    const IS_MILLISECOND = isMillisecond(timeStamp);
    // 如果是毫秒格式则转为秒格式
    if (IS_MILLISECOND) Math.floor(timeStamp /= 1000);
    // 传入的时间戳可以是数值或字符串类型，这里统一转为数值类型
    timeStamp = Number(timeStamp);
    // 获取当前时间时间戳
    const currentTime = Math.floor(Date.parse(new Date()) / 1000);
    // 判断传入时间戳是否早于当前时间戳
    const IS_EARLY = isEarly(timeStamp, currentTime);
    // 获取两个时间戳差值
    let diff = currentTime - timeStamp;
    // 如果IS_EARLY为false则差值取反
    if (!IS_EARLY) diff = -diff;
    let resStr = '';
    const dirStr = IS_EARLY ? i18n.t('before') : i18n.t('after');
    // 少于等于59秒
    if (diff <= 59) resStr = diff + i18n.t('second') + dirStr;
    // 多于59秒，少于等于59分钟59秒
    else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + i18n.t('mod_time_minute') + dirStr;
    // 多于59分钟59秒，少于等于23小时59分钟59秒
    else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + i18n.t('personal_time') + dirStr;
    // 多于23小时59分钟59秒，少于等于29天59分钟59秒
    else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + i18n.t('lab_day') + dirStr;
    // 多于29天59分钟59秒，少于364天23小时59分钟59秒，且传入的时间戳早于当前
    else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp);
    else resStr = getDate(timeStamp, 'year');
    return resStr;
};

/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorer = () => {
    const ua = window.navigator.userAgent;
    const isExplorer = (exp) => {
        return ua.indexOf(exp) > -1;
    };
    if (isExplorer('MSIE')) return 'IE';
    else if (isExplorer('Firefox')) return 'Firefox';
    else if (isExplorer('Chrome')) return 'Chrome';
    else if (isExplorer('Opera')) return 'Opera';
    else if (isExplorer('Safari')) return 'Safari';
};

/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function() {
    if (document.addEventListener) {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false);
            }
        };
    } else {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on' + event, handler);
            }
        };
    }
})();

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function() {
    if (document.removeEventListener) {
        return function(element, event, handler) {
            if (element && event) {
                element.removeEventListener(event, handler, false);
            }
        };
    } else {
        return function(element, event, handler) {
            if (element && event) {
                element.detachEvent('on' + event, handler);
            }
        };
    }
})();

/**
 * 判断一个对象是否存在key，如果传入第二个参数key，则是判断这个obj对象是否存在key这个属性
 * 如果没有传入key这个参数，则判断obj对象是否有键值对
 */
export const hasKey = (obj, key) => {
    if (key) return key in obj;
    else {
        const keysArr = Object.keys(obj);
        return keysArr.length;
    }
};

/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 */
export const objEqual = (obj1, obj2) => {
    const keysArr1 = Object.keys(obj1);
    const keysArr2 = Object.keys(obj2);
    if (keysArr1.length !== keysArr2.length) return false;
    else if (keysArr1.length === 0 && keysArr2.length === 0) return true;
    /* eslint-disable-next-line */
  else if(!keysArr1.some(key => obj1[key] != obj2[key])) {
        return true;
    }
};
/**
 * new Date 时间转换
 * @param data 当前时间 new Date
 * @returns {string}
 */
export const conversionNewDate = (data, accurate) => {
    if (!data) return data;
    const dateTime = data ? new Date(data) : new Date();
    const y = dateTime.getFullYear();
    const m = (dateTime.getMonth() + 1).toString().padStart(2, '0');
    const r = dateTime.getDate().toString().padStart(2, '0');
    const h = dateTime.getHours().toString().padStart(2, '0');
    const mm = dateTime.getMinutes().toString().padStart(2, '0');
    const ss = dateTime.getSeconds().toString().padStart(2, '0');
    return accurate ? `${y}-${m}-${r} ${h}:${mm}:${ss}` : `${y}-${m}-${r}`;
};

/**
 * 给数字不满n位的再前面补零
 * @param num 数字
 * @param n 长度
 * @returns {string}
 */
export const supplyDigit = (num, n) => {
    return (Array(n).join(0) + num).slice(-n);
};

/**
 * 计算时间离当前时间的时长，返回天，时分秒
 * @param time
 * @returns {{day: number, hours: string, minute: string, second: string}}
 */
export const countDownAlgorithm = (time) => {
    const nowTime = new Date();
    const timeCount = time.getTime() - nowTime.getTime();
    let d = 0;
    let h = 0;
    let m = 0;
    let s = 0;
    if (timeCount > 0) {
        if (timeCount >= 0) {
            d = Math.floor(timeCount / 1000 / 60 / 60 / 24); // 天
            h = Math.floor(timeCount / 1000 / 60 / 60 % 24); // 时
            m = Math.floor(timeCount / 1000 / 60 % 60); // 分
            s = Math.floor(timeCount / 1000 % 60);
        }
    }
    return { day: d, hours: supplyDigit(h, 2), minute: supplyDigit(m, 2), second: supplyDigit(s, 2) };
};

/**
 * 计算时间离当前时间的时长，返回天，时分秒
 * @param time 时间戳
 * @returns {{day: number, hours: string, minute: string, second: string}}
 */
export const countAlgorithm = (time) => {
    const nowTime = new Date();
    const timeCount = nowTime.getTime() - time;
    // let d = 0
    let h = 0;
    let m = 0;
    let s = 0;
    if (timeCount > 0) {
        if (timeCount >= 0) {
            // d = Math.floor(timeCount / 1000 / 60 / 60 / 24) // 天
            h = Math.floor(timeCount / 1000 / 60 / 60 % 24); // 时
            m = Math.floor(timeCount / 1000 / 60 % 60); // 分
            s = Math.floor(timeCount / 1000 % 60);
        }
    }
    // { hours: supplyDigit(h, 2), minute: supplyDigit(m, 2), second: supplyDigit(s, 2) }
    return supplyDigit(h, 2) + ':' + supplyDigit(m, 2) + ':' + supplyDigit(s, 2);
};

export const compareDate = (fistTime, sendTime) => {
    let tempA = fistTime.replace(/-/g, '/');
    let timeA = new Date(Date.parse(tempA)).getTime();
    if (sendTime) {
        let tempB = sendTime.replace(/-/g, '/');
        let timeB = new Date(Date.parse(tempB)).getTime();
        return timeA > timeB;
    } else {
        return timeA > new Date().getTime();
    }
};
export const throttle = (fn, delay = 2000) => {
    let lastTime;
    let timer;
    return function() {
        let args = arguments;
        // 记录当前函数触发的时间
        let nowTime = Date.now();
        if (lastTime && nowTime - lastTime < delay) {
            clearTimeout(timer);
            timer = setTimeout(function() {
                // 记录上一次函数触发的时间
                lastTime = nowTime;
                // 修正this指向问题
                fn.apply(this, args);
            }, delay);
        } else {
            lastTime = nowTime;
            fn.apply(this, args);
        }
    };
};
// 动态加载js文件
export const loadJS = (url, callback) => {
    let script = document.createElement('script');
    let fn = callback || function() {};
    script.type = 'text/javascript';
    //IE
    if (script.readyState) {
        script.onreadystatechange = function() {
            if (script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null;
                fn();
            }
        };
    } else {
        //其他浏览器
        script.onload = () => {
            fn();
        };
        script.onerror = () => {
            fn();
        };
    }
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
};
// 动态删除js/css文件
export const removejscssfile = (filename, filetype) => {
    var targetelement = (filetype === 'js') ? 'script' : (filetype === 'css') ? 'link' : 'none';
    var targetattr = (filetype === 'js') ? 'src' : (filetype === 'css') ? 'href' : 'none';
    var allsuspects = document.getElementsByTagName(targetelement);

    for (var i = allsuspects.length; i >= 0; i--) {
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) !== -1) { allsuspects[i].parentNode.removeChild(allsuspects[i]); };
    }
};
// 清除登录痕迹
export const clearLoginStorage = () => {
    window.localStorage.removeItem('token');
    window.localStorage.removeItem('userInfo');
    window.localStorage.removeItem('loginUser');
    window.localStorage.removeItem('login-logo');
    window.localStorage.removeItem('usrSteUsrId');
    window.localStorage.removeItem('wizbank-user-auth');
};
// 计算总学习时长(秒转分秒)
export const fmtHours = (seconds) => {
    if (seconds && typeof seconds === 'number') {
        // return this.$moment.utc(seconds * 1000).format('HH:mm:ss')
        // const hh = Math.floor(seconds / (60 * 60)) < 10 ? '0' + Math.floor(seconds / (60 * 60)) : Math.floor(seconds / (60 * 60));
        // const mm = Math.floor((seconds % (60 * 60)) / 60) < 10 ? '0' + Math.floor((seconds % (60 * 60)) / 60) : Math.floor((seconds % (60 * 60)) / 60);
        const hh = Math.floor(seconds / (60 * 60));
        const mm = Math.floor((seconds % (60 * 60)) / 60);
        return (hh ? hh + i18n.t('hour') : '') + (mm ? mm + i18n.t('minute') : '');
    } else {
        return '';
    }
};
// 计算总学习时长(秒转时分秒)
export const fmtHours1 = (seconds, vm) => {
    if (seconds && typeof seconds === 'number') {
        const hh = Math.floor(seconds / (60 * 60)); // 时
        const mm = Math.floor((seconds % (60 * 60)) / 60); // 分
        const ss = Math.floor(seconds % 60);
        return (hh ? hh + i18n.t('hour') : '') + (mm ? mm + i18n.t('minute') : '') + (ss ? ss + i18n.t('second') : '');
    } else {
        return '';
    }
};

const CWN_ENC_KEY_1 = 157862245;
const CWN_ENC_KEY_2 = 32211;
const CWN_ENC_SEPARATOR = '_';
// ID加密
export const cwnEncrypt = (id) => {
    return String(Number(id) + CWN_ENC_KEY_1) + CWN_ENC_SEPARATOR + String(CWN_ENC_KEY_1 - Number(id) - CWN_ENC_KEY_2);
};
// 加密id 解密
export const cwnDecrypt = (encId) => {
    const ids = splitToLong(encId, CWN_ENC_SEPARATOR);
    let decrId = 0;
    if (ids != null && ids.length === 2) {
        let key1 = ids[0];
        const key2 = ids[1];

        key1 = key1 - CWN_ENC_KEY_1;
        const tempKey = key2 + key1 + CWN_ENC_KEY_2;
        if (tempKey === CWN_ENC_KEY_1) {
            decrId = key1;
        } else {
            decrId = Number(encId);
        }
    }
    return decrId;
};

function splitToLong(encryptStr, delimiter) {
    var res = [];
    if (encryptStr != null && typeof (encryptStr) !== 'undefined') {
        var q = encryptStr.split(delimiter);
        for (var i = 0; i < q.length; i++) {
            res[i] = Number(q[i]);
        }
    } else {
        res[0] = 0;
    }
    return res;
}
